<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Address, Promo, MoneyLog, Region, Cart, Product, Coupon, OrderProduct, Order, Pkey, Agent, Payment, Wechat, UserLevel, Riderlist, RiderStreet, IntergralLog, Message};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class User extends Base
{

    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
        ], [
            'code.require' => '微信授权码不能为空',
            'iv.require' => 'IV数据不能为空',
            'encryptedData.require' => 'encryptedData数据不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $model = new Users();
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        try {
            $res = $app->auth->session($data['code']);
        } catch (\Exception $e) {
            $this->result([], 1, '获取信息错误,请重试');
        }
        $time = $config['tokenExpireHours'];
        if (empty($res['session_key']) || empty($res['openid'])) {
            $this->result([], 1, '登录失败,请重试');
        }
        $data['type'] = 1;
        $unique = 'session_key' . $res['openid'] . $data['type'];
        Redis::setex($unique, 3 * 86400, $res['session_key']);
        //判断用户是否已经注册
        $user = $model->where(['openid' =>  $res['openid'], 'type' => $data['type']])->find();
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }
        $save = [
            'session_key' => $res['session_key'],
            'openid' => $res['openid'],
            'wxopenid' => $res['openid'],
            'gender' => $decryptedData['gender'] ?? 0,
            'province' => $decryptedData['province'] ?? '',
            'city' => $decryptedData['city'] ?? '',
            // 'avatarUrl' => $decryptedData['avatarUrl'] ?? '',
            'avatarUrl' => '',
            'country' => $decryptedData['country'] ?? '',
            'nickName' =>  preg_replace('/[\xf0-\xf7].{3}/', '', $decryptedData['nickName'] ?? ''),
        ];
        if (empty($save['nickName'])) {
            $save['nickName'] = '微信用户';
        }
        $savetime = !empty($user['created']) ? $user['created'] : date('Y-m-d H:i:s');
        if (!empty($data['puser']) && empty($user['pid']) && $savetime >= date('Y-m-d H:i:s', time() - 5 * 3600)) {
            $save['pid'] = $model->where('code', $data['puser'])->value('id') ?? 0;
        }
        if ($user) {
            $res2 = $model->allowfield(true)->save($save, ['id' => $user['id']]);
        } else {
            $save['code'] = recode($model);
            $res2 = $model->allowfield(true)->save($save);
            $user = $model->where(['openid' => $save['openid'], 'type' => $data['type']])->find();
        }
        if ($res2 && !empty($user)) {
            $token = 'user_' . md5(time() . $user['code']);
            Redis::setex($token, $time, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        }
        $this->result([], 1, '登录失败');
    }

    public function setmobile()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
            'type' => 'require|in:1,2'
        ], [
            'code.require' => 'code不能为空',
            'iv.require' => 'iv不能为空',
            'encryptedData.require' => 'encryptedData不能为空',
            'type.require' => '类型不能为空',
            'type.in' => '类型参数不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        $user = (new Users())->where('id', $this->request->user_id)->find();
        if (!empty($user['mobile'])) {
            $this->result([], 1, '您已绑定手机号码,无需重复绑定');
        }
        if ($data['type'] == 1) {
            try {
                $res = $app->auth->session($data['code']);
            } catch (\Exception $e) {
                $this->result([], 1, '获取秘钥错误,请重试');
            }
        }
        if ($data['type'] == 2) {
            try {
                $res = (new Douyin())->session($data['code']);
            } catch (\Exception $e) {
                $this->result([], 1, '获取秘钥错误,请重试');
            }
        }
        if (empty($res['session_key']) || empty($res['openid'])) {
            $this->result([], 1, '操作失败,请重试');
        }
        //存session_key
        $unique = 'session_key' . $res['openid'] . $data['type'];
        $frtimes = Redis::get($unique);
        Redis::setex($unique, 3 * 86400, $res['session_key']);
        if ($frtimes) {
            $res['session_key'] = $frtimes;
        }
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, '解析失败，请重试');
        }
        if (!empty($decryptedData['purePhoneNumber'])) {
            $data['mobile'] = $decryptedData['purePhoneNumber'];
            //查找手机号码是否已绑定
            $user = (new Users())->where('mobile', $data['mobile'])->find();
            if (!empty($user)) {
                $this->result([], 1, '授权失败,手机号码已被绑定');
            }
            $res = (new Users())->where('id', $this->request->user_id)->update(['mobile' => $data['mobile']]);
            if ($res) {
                $this->result(['mobile' => $data['mobile']], 0, '授权成功');
            }
        }
        $this->result([], 1, '授权失败');
    }

    public function mlogin()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
            'type' => 'require|in:1,2'
        ], [
            'code.require' => 'code不能为空',
            'iv.require' => 'IV不能为空',
            'encryptedData.require' => 'encryptedData不能为空',
            'type.require' => '类型不能为空',
            'type.in' => '类型参数不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $config = config('wechat.');
        $time = $config['tokenExpireHours'];
        $app = Factory::miniProgram($config);
        if ($data['type'] == 1) {
            try {
                $res = $app->auth->session($data['code']);
            } catch (\Exception $e) {
                $this->result([], 1, '获取秘钥错误,请重试');
            }
        }
        if ($data['type'] == 2) {
            try {
                $res = (new Douyin())->session($data['code']);
            } catch (\Exception $e) {
                $this->result([], 1, '获取秘钥错误,请重试');
            }
        }
        if (empty($res['session_key']) || empty($res['openid'])) {
            $this->result([], 1, '操作失败,请重试');
        }
        //存session_key
        $unique = 'session_key' . $res['openid'] . $data['type'];
        $frtimes = Redis::get($unique);
        Redis::setex($unique, 3 * 86400, $res['session_key']);
        if ($frtimes) {
            $res['session_key'] = $frtimes;
        }
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, '操作失败,请重试');
        }
        if (!empty($decryptedData['purePhoneNumber'])) {
            $data['mobile'] = $decryptedData['purePhoneNumber'];
            $user = (new Users())->where('mobile', $data['mobile'])->find();
            if (empty($user)) {
                $this->result([], 1, '请授权登陆绑定手机号后再尝试');
            }
            //更新openid用于登陆
            if ($user['type'] == 2 && empty($user['wxopenid'])) {
                (new Users())->where('id', $user['id'])->update(['wxopenid' => $res['openid']]);
            }
            if ($user['type'] == 1 && empty($user['dyopenid'])) {
                (new Users())->where('id', $user['id'])->update(['dyopenid' => $res['openid']]);
            }
            $token = 'user_' . md5(time() . $user['code']);
            Redis::setex($token, $time, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        }
        $this->result([], 1, '登陆失败,请重试');
    }

    public function qrcode()
    {
        $user = $this->request->user;
        if ($user['type'] == 1) {
            $name = 'appcode' . $user['id'] . '.png';
            $qcode = url('/uploads/wechat/' . $name, '', '', true);
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/wechat/";
            if (!file_exists($path . $name)) {
                $config = config('wechat.');
                try {
                    if (!is_dir($path)) {
                        mkdir($path, 0777, true);
                    }
                    $app = Factory::miniProgram($config);
                    $rm = $app->app_code->getUnlimit('invite=' . $user['code'], [
                        'page'  => '',
                        'width' => 600,
                        'auto_color' => false,
                        'line_color' => [
                            'r' => 0,
                            'g' => 160,
                            'b' => 232,
                        ],
                    ]);
                    if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                        $rm->save($path, $name);
                    }
                } catch (\Exception $e) {
                    $this->result([], 1, $e->getMessage());
                }
            }
            $this->result($qcode, 0, '获取成功');
        } else {
            $name = 'appcode' . $user['id'] . '.png';
            $qcode = url('/uploads/zijie/' . $name, '', '', true);
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/zijie/";
            if (!file_exists($path . $name)) {
                try {
                    $res = (new Douyin())->qrcode('pages/index/index?scene=invite=' . $user['code']);
                    if ($res) {
                        file_put_contents($path . $name, $res);
                    }
                } catch (\Exception $e) {
                    $this->result([], 1, '获取信息错误,请重试');
                }
            }
            $this->result($qcode, 0, '获取成功');
        }
    }


    public function address()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'street' => 'require',
                'address' => 'require',
                'is_default' => 'require|in:1,2',
                'getaddress' => 'require',
                'lat' => 'require',
                'lon' => 'require',
            ], [
                'name.require' => '联系人姓名不能为空',
                'mobile.require' => '联系人电话不能为空',
                'street.require' => '街道ID不能为空',
                'address.require' => '具体地址不能为空',
                'getaddress.require' => '定位地址不能为空',
                'is_default.require' => '默认类型不能为空',
                'is_default.in' => '默认类型不正确',
                'lat.require' => '经度不能为空',
                'lon.require' => '纬度不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $streets = getdrees($data['street']);
            if (empty($streets['street']) || empty($streets['area']) || empty($streets['city']) || empty($streets['province'])) {
                $this->result([], 1, '添加错误，请重试或退出页面重新编辑');
            }
            $data['street'] = $streets['street'];
            $data['area'] = $streets['area'];
            $data['city'] = $streets['city'];
            $data['province'] = $streets['province'];
            $data['user_id'] = $this->request->user_id;
            $addressmodel = new Address();
            Db::startTrans();
            try {
                (new Address())->where('user_id', $this->request->user_id)->update(['is_default' => 1]);
                if (!empty($data['id'])) {
                    $addressmodel->allowfield(true)->save($data, ['id' => $data['id']]);
                } else {
                    $addressmodel->allowfield(true)->save($data);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败');
            }
            $this->result([], 0, '操作成功');
        } else {
            $addressmodel = new Address();
            $result = $addressmodel->where('user_id', $this->request->user_id)->order('is_default desc')->field('user_id,created', true)->select();
            foreach ($result as $results) {
                $address_name = getdrees($results['street'], 1);
                $results['province_name'] = $address_name['province'];
                $results['city_name'] = $address_name['city'];
                $results['area_name'] = $address_name['area'];
                $results['street_name'] = $address_name['street'];
            }
            $this->result($result, 0, '操作成功');
        }
    }


    public function address_del()
    {
        $id = $this->request->post('id/d', 0);
        $addressmodel = new Address();
        $result = $addressmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function cart_del()
    {
        $id = $this->request->post('ids/s');
        $ids  = json_decode($id, true) ?? [];
        if (empty($ids)) {
            $this->result([], 1, '数据为空，操作失败');
        }
        $model = new Cart();
        $result = $model->where(['user_id' => $this->request->user_id, 'id' => $ids])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function cart()
    {
        if ($this->request->isPost()) {
            if (empty($this->request->user_id)) {
                $this->result(null, 999, '请授权登陆账号');
            }
            $data = $this->request->post();
            $validate = new Validate([
                'productid' => 'require',
                'number' => 'require',
                'type' => 'require|in:1,2'
            ], [
                'productid.require' => '产品ID不能为空',
                'number.require' => '产品数目不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $product = (new Product())->alias('p')
                ->join('agent a', 'p.agentid = a.id')
                ->where(['p.id' => $data['productid'], 'p.isdel' => 1, 'p.isshow' => 1, 'a.status' => 1])
                ->field('p.*')
                ->find();
            if (empty($product)) {
                $this->result([], 1, '产品已下架');
            }
            //查询是否已经添加购物车
            $mycart = (new Cart())->where(['productid' => $data['productid'], 'user_id' => $this->request->user_id])->find();
            $number = (int)$data['number'] ?? 0;
            if ($data['type'] == 1 && !empty($mycart)) {
                $number += $mycart['number'];
            }
            $save = [
                'user_id' => $this->request->user_id,
                'cate' =>  $product['cate'],
                'agentid' => $product['agentid'],
                'productid' => $data['productid'],
                'number' => $number
            ];
            if (!empty($mycart)) {
                if ($number <= 0) {
                    $res =  (new Cart())->where('id', $mycart['id'])->delete();
                } else {
                    $res =  (new Cart())->allowfield(true)->save($save, ['id' => $mycart['id']]);
                }
            } else {
                if ($number <= 0) {
                    $res = true;
                } else {
                    $res =  (new Cart())->allowfield(true)->save($save);
                }
            }
            if ($res) {
                $this->result(['number' => $number], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $agentid = $this->request->get('agentid/d', 0);
            $goods = (new Cart())->alias('c')
                ->join('product p', 'p.id = c.productid')
                ->where(['p.isdel' => 1, 'p.isshow' => 1, 'c.agentid' => $agentid, 'c.user_id' => $this->request->user_id])
                ->field('c.id,c.number,c.productid,p.images,p.title,p.price')
                ->select();
            $total = 0;
            $count = 0;
            foreach ($goods  as $good) {
                $total += $good['price'] * $good['number'];
                $count += $good['number'];
            }
            $list['goods'] = $goods;
            $list['count'] = $count;
            $list['total'] = $total;
            $this->result($list, 0, '获取成功');
        }
    }

    public function keyend()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'key' => 'require'
        ], [
            'key.require' => '兑换码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        //查询兑换码是否存在
        $key = (new Pkey())->where(['code' => $data['key'], 'status' => 1])->find();
        if (empty($key)) {
            $this->result([], 1, '兑换码不存在或已被使用');
        }
        //兑换码存在查询活动是否还在继续
        $promo = (new Promo())->where(['id' => $key['promoid'], 'status' => 1, 'type' => 1])->find();
        if (empty($promo)) {
            $this->result([], 1, '兑换码已失效');
        }
        $coupons = [];
        $promo['coupon'] = json_decode($promo['coupon'], true) ?? [];
        foreach ($promo['coupon'] as $coupon) {
            $coupon['type'] = implode(',', $coupon['type']);
            $coupons[] = [
                'type' => 1,
                'types' => 2,
                'user_id' => $this->request->user_id,
                'agentid' => $promo['agentid'],
                'productid' => $coupon['type'],
                'number' => 1,
                'status' => 1,
                'endtime' => date('Y-m-d H:i:s', time() + 86400 * $coupon['days']),
                'promo' => $promo['id'],
                'keyid' => $key['id'],
                'btmoney' => $coupon['money']
            ];
        }
        Db::startTrans();
        try {
            if (count($coupons) > 0) {
                (new Coupon())->allowfield(true)->saveAll($coupons);
            }
            if ($this->request->user['level'] == 1) {
                (new Users())->where(['id' => $this->request->user_id])->update(['level' => 2]);
            }
            if ($promo['agentid'] > 0) {
                (new Agent())->MoneyEdit2($promo['agentid'], 2, $promo['money'], '使用兑换码', 0);
            }
            (new Pkey())->where('id', $key['id'])->update(['status' => 2, 'user_id' => $this->request->user_id]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result([], 0, '兑换成功,请注意卡券或余额的变动');
    }

    public function getcoupon()
    {
        $data = $this->request->get();
        $agentid = (int)($data['agentid'] ?? 0);
        $total = (float)($data['money'] ?? 0);
        $list = (new Coupon())
            ->where(['user_id' => $this->request->user_id, 'status' => 1, 'types' => 1])
            ->field('id,type,types,agentid,productid,getmoney,system,money,status,endtime,text,number,created')
            ->order('id desc');
        if (!empty($data['productid'])) {
            $list = $list->where(['agentid' => [0, $agentid]]);
        }
        $list = $list->select();
        foreach ($list as $k => $lists) {
            $lists['agent_name'] = (new Agent())->where('id',$lists['agentid'])->value('nickname') ?? '';
            if ($lists['type'] == 1) {
                $lists['title'] = '原价满' . (float)$lists['getmoney'] . '元立减' . (float)$lists['money'] . '元';
            }
            // if ($lists['type'] == 2) {
            //     $lists['title'] = '区域满减券';
            // }
            // if ($lists['system'] == 4) {
            //     $lists['title'] = '新用户满减券';
            // }
            $lists['text'] = '本券最终解释权为平台所有。';
            if (empty($total)) {
                $lists['iscan'] = 2;
                if ($lists['types'] == 2 && $lists['number'] <= 0) {
                    unset($list[$k]);
                }
            } else {
                if ($lists['types'] == 2) {
                    unset($list[$k]);
                } else {
                    $lists['iscan'] = 1;
                    if ($lists['type'] == 1) {
                        if ($total >= $lists['getmoney']) {
                            $lists['iscan'] = 2;
                        }
                    }
                    if ($lists['type'] == 2) {
                        if ($total >= $lists['getmoney'] && $lists['agentid'] == $agentid) {
                            $lists['iscan'] = 2;
                        }
                    }
                }
            }
        }
        if (count($list) > 0) {
            $list = array_values($list->toArray());
        }
        $this->result($list, 0, '获取成功');
    }

    public function putorder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'type' => 'require|in:1,2',
            'productid' => 'require',
            'addressid' => 'require',
            'agentid' => 'require|gt:0'
        ], [
            'type.require' => '类型不能为空',
            'type.in' => '类型不正确',
            'productid.require' => '规格ID不能为空',
            'addressid.require' => '联系信息不能为空',
            'agentid.require' => '门店ID信息错误',
            'agentid.gt' => '门店ID信息错误',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (empty($data['appointment'])) {
            $data['appointment'] = date('Y-m-d H:i', time() + 3600);
        } else {
            $data['appointment'] = date('Y-m-d H:i', strtotime($data['appointment']));
        }
        Log::write($data, 'test');
        if (!is_array($data['productid'])) {
            $data['productid'] = json_decode($data['productid'], true) ?? [];
        }
        if (empty($data['productid']) || !is_array($data['productid'])) {
            $this->result([], 1, '产品数据错误');
        }
        if (!empty($data['cartid'])) {
            $data['cartid'] = json_decode($data['cartid'] ?? '', true) ?? [];
        }
        //查询地址是否存在
        $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
        if (empty($address)) {
            $this->result([], 1, '地址信息不存在');
        }
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $address['lat'] . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $address['lat'] . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $address['lon'] . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $order = [
            'type' => $data['type'],
            'user_id' => $this->request->user_id,
            'ordersn' => reordersn(new Order()),
            'agentid' =>  $data['agentid'],
            'name' => $address['name'],
            'mobile' => $address['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'area' => $address['area'],
            'street' => $address['street'],
            'posaddress' => $address['getaddress'],
            'address' => $address['address'],
            'lat' => $address['lat'],
            'lon' => $address['lon'],
            'appointment' => $data['appointment'],
            'info' => $data['info'] ?? '',
            'status' => 1,
            'coupon' => !empty($data['coupon']) ? $data['coupon'] : 0,
            'cmoney' => 0,
            'dict' => 0,
            'isfirst' => 1,
            'ptotal' => 0,
            'ccount' => 0,
            'total' => 0,
            'sendmoney' =>  0
        ];
        $orderproduct = [];
        $agentinfo = (new Agent())->field('*,' . $filed)->where(['id' => $data['agentid'], 'status' => 1])->find();
        if (empty($agentinfo)) {
            $this->result([], 1, '店铺已下架,请切换店铺下单');
        }
        if ($agentinfo['dist'] > $agentinfo['maxkm'] && $data['type'] == 1) {
            $this->result([], 1, '配送超出商家服务范围');
        }
        if (!empty($data['payment']) && $data['payment'] == 1 && $agentinfo['payopen'] == 1) {
            $this->result([], 1, '该商家线下支付通道暂时关闭');
        }
        $agentid = $agentinfo['id'];
        foreach ($data['productid'] as $product) {
            if (empty($product['id'])  || empty($product['number'])) {
                $this->result([], 1, '产品参数错误');
            }
            //查询规格是否存在
            $products = (new Product())->where(['isdel' => 1, 'isshow' => 1, 'id' => $product['id'], 'agentid' => $agentid])->find();
            if (empty($products)) {
                $this->result([], 1, '产品已下架,请刷新页面重新提交订单');
            }
            //查找下面有没有相关服务人员
            $orderproduct[] = [
                'ordersn' => $order['ordersn'],
                'agentid' => $agentid,
                'cate' => $products['cate'],
                'subcate' => $products['subcate'],
                'productid' => $products['id'],
                'title' =>  $products['title'],
                'descs' =>  $products['descs'],
                'images' =>  $products['images'],
                'price' =>  $products['price'],
                'number' =>  $product['number'],
                'numbers' =>  $product['number'],
                'type' => $products['type'],
                'cnumber' => 0,
                'cid' => ''
            ];
            $order['ptotal'] += $product['number'] * $products['price'];
        }
        if (!empty($data['coupon'])) {
            $coupon = (new Coupon())->where(['id' => $data['coupon'], 'agentid' => [0, $agentid], 'user_id' => $this->request->user_id, 'status' => 1, 'types' => 1])->find();
            if (empty($coupon)) {
                $this->result([], 1, '优惠券不存在或已使用');
            }
            if ($coupon['getmoney'] > $order['ptotal']) {
                $this->result([], 1, '优惠券未达到使用条件');
            }
            if ($coupon['money'] > $order['ptotal']) {
                $order['cmoney'] = $order['ptotal'];
            } else {
                $order['cmoney'] = $coupon['money'];
            }
        }
        if ($order['ptotal'] < $agentinfo['starsendmoney']) {
            $this->result([], 1, '商品总价低于商家起送价');
        }
        $agentinfo['psmoney'] = (float)$agentinfo['psmoney'];
        $order['sendmoney'] = $agentinfo['psmoney'];
        $order['total'] = $order['ptotal'] + $order['sendmoney'] - $order['cmoney'];
        $text = '下单成功，请前往支付';
        if ($order['total'] <= 0) {
            $order['total'] = 0;
            $order['status'] = 2;
            $text = '下单成功';
        }
        Db::startTrans();
        try {
            (new Order())->save($order);
            (new OrderProduct())->allowfield(true)->saveAll($orderproduct);
            if (!empty($data['cartid'])) {
                (new Cart())->where(['id' => $data['cartid'], 'user_id' => $this->request->user_id])->delete();
            }
            if (!empty($coupon)) {
                (new Coupon())->where(['id' => $coupon['id'], 'user_id' => $this->request->user_id, 'status' => 1])->update(['status' => 3]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result(['ordersn' => $order['ordersn'], 'status' => $order['status']], 0, $text);
    }

    public function info()
    {
        $user = $this->request->user;
        $result = [
            'id' => $user['id'],
            'code' => $user['code'],
            'nickName' => $user['nickName'],
            'avatarUrl' => $user['avatarUrl'],
            'mobile' => $user['mobile'],
            'money' => (float)$user['money'],
            'coupon' => (new Coupon())->where(['user_id' => $user['id'], 'status' => 1])->count(),
            'integral' => (float)$user['integral'],
            'integralall' => (float)$user['integralall'],
        ];
        $this->result($result, 0, '获取成功');
    }

    public function integrallog()
    {
        $type = $this->request->get('type/d', 1);
        if ($type == 2) {
            $model = new MoneyLog();
        } else {
            $model = new IntergralLog();
        }
        $list = $model
            ->where('user_id', $this->request->user_id)
            ->field('created,info,money')
            ->order('id desc')
            ->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '获取成功');
    }

    public function orderstatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'ordersn' => 'require',
            'status' => 'require|in:2,4,5'
        ], [
            'ordersn.require' => '订单编号不能为空',
            'status.require' => '状态不能为空',
            'status.in' => '状态不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where('ordersn', $data['ordersn'])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        switch ($data['status']) {
            case '2':
                if ($order['status'] != 1) {
                    $this->result([], 1, '订单不处于支付状态');
                }
                if (empty($data['payment'])) {
                    $this->result([], 1, '订单支付方式错误');
                }
                if ($data['payment'] == 1) {
                    //支付订单
                    Db::startTrans();
                    try {
                        (new Order())->where('id', $order['id'])->update(['status' => $data['status'], 'paytime' => date('Y-m-d H:i:s'), 'payment' => $data['payment']]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                } elseif ($data['payment'] == 2) {
                    //支付订单 返回微信信息
                    $ordersn = repayorder(new Payment());
                    $wechatarr = [
                        'pay_title' => '项目订单，编号' . $order['ordersn'],
                        'payment_id' =>  $ordersn,
                        'money' => $order['total'],
                        'ip' => $this->request->ip(),
                        'user_id' => $this->request->user_id,
                        'params' => json_encode(['trade_type' => 'JSAPI'], true)
                    ];
                    $list = (new Wechat())->pay($wechatarr);
                    if ($list['status'] == true) {
                        //存储支付订单记录
                        $res = (new Payment())->save(['user_id' => $this->request->user_id, 'money' => $order['total'], 'type' => 1, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $order['ordersn']]);
                        if ($res) {
                            $this->result($list, 0, '获取成功');
                        } else {
                            $this->result([], 1, '获取失败,请重试');
                        }
                    } else {
                        $this->result([], 1, $list['msg'] ?? '获取失败');
                    }
                } elseif ($data['payment'] == 3) {
                    //支付订单 返回微信信息
                    $ordersn = repayorder(new Payment());
                    $wechatarr = [
                        'pay_title' => '项目订单，编号' . $order['ordersn'],
                        'payment_id' =>  $ordersn,
                        'money' => $order['total'],
                        'ip' => $this->request->ip(),
                        'user_id' => $this->request->user_id,
                        'params' => json_encode(['trade_type' => 'JSAPI'], true)
                    ];
                    $list = (new Douyin())->pay($wechatarr);
                    if ($list['status'] == true) {
                        //存储支付订单记录
                        $res = (new Payment())->save(['user_id' => $this->request->user_id, 'paytype' => 2, 'money' => $order['total'], 'type' => 1, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $order['ordersn']]);
                        if ($res) {
                            $this->result($list, 0, '获取成功');
                        } else {
                            $this->result([], 1, '获取失败,请重试');
                        }
                    } else {
                        $this->result([], 1, $list['msg'] ?? '获取失败');
                    }
                } elseif ($data['payment'] == 4) {
                    //判断余额是否足够
                    if ($this->request->user['money'] < $order['total']) {
                        $this->result([], 1, $list['msg'] ?? '余额不足');
                    }
                    $user = $this->request->user;
                    Db::startTrans();
                    try {
                        (new Order())->where('id', $order['id'])->update(['status' => $data['status'], 'paytime' => date('Y-m-d H:i:s'), 'payment' => $data['payment']]);
                        (new Users())->MondyEdit($user['id'], $user['money'], -$order['total'], 2, 0, '支付订单');
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                }
                break;
            case '4':
                if ($order['status'] != 3) {
                    $this->result([], 1, '订单状态不可完成');
                }
                //完成订单
                $user = $this->request->user;
                Db::startTrans();
                try {
                    (new Order())->where('id', $order['id'])->update(['status' => $data['status'], 'endtime' => date('Y-m-d H:i:s')]);
                    (new Users())->IntergralEdit($user['id'], $user['integral'], $order['total'], 1, $order['id'], '下单赠送');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->result([], 1, $e->getMessage());
                }
                $this->result([], 0, '操作成功');
                break;
            case '5':
                $msg = '取消成功';
                if ($order['status'] != 1 && $order['status'] != 2) {
                    $this->result([], 1, '订单状态不可取消');
                }
                //取消
                $data['refund'] = $order['refund'];
                if ($order['status'] == 2 && $order['total'] > 0 && $order['payment'] > 1) {
                    $data['refund'] = 2;
                    $msg = "取消成功，退款稍后原路返回";
                }
                Db::startTrans();
                try {
                    if ($order['coupon'] > 0) {
                        (new Coupon())->where('id', $order['coupon'])->update(['status' => 1]);
                    }
                    (new Order())->where('id', $order['id'])->update([
                        'status' => $data['status'],
                        'caceltime' => date('Y-m-d H:i:s'),
                        'refund' => $data['refund']
                    ]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->result([], 1, $e->getMessage());
                }
                $this->result([], 0, $msg);
                break;
            default:
                $this->result([], 1, '状态出错');
                break;
        }
    }

    public function recharge()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'money' => 'require|gt:0',
            'payment' => 'require|in:2,3'
        ], [
            'money.require' => '充值金额不能为空',
            'money.gt' => '充值金额必须大于0',
            'payment.require' => '支付方式不能为空',
            'payment.in' => '支付方式不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $this->result([], 1, '充值通道已关闭');
        //支付订单 返回微信信息
        $ordersn = repayorder(new Payment());
        $wechatarr = [
            'pay_title' => '充值余额支付订单',
            'payment_id' =>  $ordersn,
            'money' => $data['money'],
            'ip' => $this->request->ip(),
            'user_id' => $this->request->user_id,
            'params' => json_encode(['trade_type' => 'JSAPI'], true)
        ];
        if (empty($data['payment']) || $data['payment'] == 2) {
            $list = (new Wechat())->pay($wechatarr);
            if ($list['status'] == true) {
                //存储支付订单记录
                $res = (new Payment())->save(['user_id' => $this->request->user_id, 'money' => $data['money'], 'type' => 4, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $this->request->user_id, 'paytype' => 1]);
                if ($res) {
                    $this->result($list, 0, '获取成功');
                } else {
                    $this->result([], 1, '获取失败,请重试');
                }
            } else {
                $this->result([], 1, $list['msg'] ?? '获取失败');
            }
        } elseif ($data['payment'] == 3) {
            $list = (new Douyin())->pay($wechatarr);
            if ($list['status'] == true) {
                //存储支付订单记录
                $res = (new Payment())->save(['user_id' => $this->request->user_id, 'money' => $data['money'], 'type' => 4, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $this->request->user_id, 'paytype' => 2]);
                if ($res) {
                    $this->result($list, 0, '获取成功');
                } else {
                    $this->result([], 1, '获取失败,请重试');
                }
            } else {
                $this->result([], 1, $list['msg'] ?? '获取失败');
            }
        }
        $this->result([], 1, $list['msg'] ?? '获取失败');
    }

    public function orderlist()
    {
        if (empty($this->request->user_id)) {
            $this->result([], 0, '获取成功');
        }
        $status = $this->request->get('status/d', '');
        $list = (new Order())->order('id desc');
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->where('user_id', $this->request->user_id)->field('id,type,agentid,ordersn,status,total,refund,created')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['tnumber'] = 0;
            $ordergoods = (new OrderProduct())->field('productid,title,descs,images,price,number,cnumber')->where(['ordersn' => $lists['ordersn']])->select();
            foreach ($ordergoods as $goods) {
                $lists['tnumber'] += $goods['number'];
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
            $lists['agent_name'] = (new Agent())->where('id', $lists['agentid'])->value('nickname') ?? '';
        }
        $this->result($list, 0, '获取成功');
    }


    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where('id', $id)->field('id,agentid,sendmoney,type,payment,ordersn,ptotal,cmoney,total,appointment,created,info,status,street,name,mobile,posaddress,address,refund')->find();
        if ($list) {
            $list['type_text'] = $list->type_text;
            $list['status_text'] = $list->status_text;
            $list['payment_text'] = $list->payment_text;
            $goods = (new OrderProduct())->where('ordersn', $list['ordersn'])->field('images,number,title,price,cnumber')->select();
            $list['good'] = $goods;
        }
        $this->result($list, 0, '获取成功');
    }

    public function userlevel()
    {
        $list = (new UserLevel())->field('zhekou,money,contents,protocol,isopen')->where('level', 2)->find();
        $user_id = $this->request->user_id ?? 0;
        $list['zhekou'] = $list['zhekou'] / 10;
        $this->result($list, 0, '获取成功');
    }

    public function  message()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'message' => 'require',
                'type' => 'require|in:1,2,3',
            ], [
                'message.require' => '反馈内容为空',
                'type.require' => '反馈类型不能为空',
                'type.in' => '反馈类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['messtype'] = $data['type'];
            $data['type'] = 1;
            $data['user_id'] = $this->request->user_id;
            if (!empty($data['images'])) {
                $images = json_decode($data['images'] ?? '', true) ?? [];
                if (is_array($images) && count($images) > 0) {
                    $data['images'] = json_encode($images, true);
                } else {
                    $data['images'] = '';
                }
            } else {
                $data['images'] = '';
            }
            $res = (new Message())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败');
        } else {
            $list = (new Message())->order('id desc');
            $list = $list->where(['user_id' =>  $this->request->user_id, 'type' => 1])
                ->field('message,reply,mobile,created,images,messtype')
                ->paginate(20, false, ['query' => $this->request->param()])->each(function ($item) use ($list) {
                    $item['images'] = json_decode($item['images'], true) ?? [];
                    $item['type_text'] = $item->type_text;
                    return $item;
                });
            $this->result($list, 0, '查询完成');
        }
    }

    public function invitlist()
    {
        $list = [
            'people' => 0,
            'coupon' => 0,
            'coupon_money' => 0,
            'list' => []
        ];
        $list['people'] = [];
        $user = (new Users())->where('pid', $this->request->user_id)->field('nickName,avatarUrl,DATE_FORMAT(created, "%Y-%m-%d" ) as createds')->select();
        $coupon = (new Coupon())->where(['user_id' => $this->request->user_id, 'system' => 2])->field('money')->select()->toArray() ?? [];
        $list['people'] = count($user);
        $list['list'] = $user;
        $list['coupon'] = count($coupon);
        $list['coupon_money'] = (float)array_sum(array_column($coupon, 'money')) ?? 0;
        $this->result($list, 0, '查询完成');
    }


    public function riderapply()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'mobile' => 'require',
                'password' => 'require',
                'name' => 'require',
                'cards' => 'require',
                'positive' => 'require',
                'negative' => 'require',
                'street' => 'require'
            ], [
                'mobile.require' => '手机号不能为空',
                'password.require' => '密码不能为空',
                'name.require' => '名称不能为空',
                'cards.require' => '身份证号不能为空',
                'positive.require' => '身份证正面不能为空',
                'negative.require' => '身份证反面不能为空',
                'street.require' => '街道ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '联系电话格式不正确');
            }
            $data['password'] = md5(md5($data['password']));
            $data['lat'] = $data['lat'] ?? 0;
            $data['lng'] = $data['lng'] ?? 0;
            Log::write($data, 'getlons');
            $streets = getlatlon($data['lat'], $data['lng'], 3);
            if (empty($streets['street'])) {
                $streets = getdrees($data['street'], 3);
            }
            if (empty($streets['street']) || empty($streets['area']) || empty($streets['city']) || empty($streets['province'])) {
                $this->result([], 1, '地址信息错误，请重新选择或刷新页面重试');
            }
            //代理ID
            if (empty($streets['agentid'])) {
                $this->result([], 1, '当前街道暂未开放申请');
            }
            //查一下是否全国代理
            $isall = (new AgentArea())->where(['type' => 1, 'agentid' => $streets['agentid']])->find();
            if (!empty($isall)) {
                $this->result([], 1, '当前区域不支持申请');
            }
            $save = [
                'user_id' => $this->request->user_id,
                'mobile' => $data['mobile'],
                'password' => $data['password'],
                'name' => $data['name'],
                'cards' => $data['cards'],
                'positive' => $data['positive'],
                'negative' => $data['negative']
            ];
            $rider = (new RiderList())->where(['mobile' => $data['mobile']])->find();
            $riderid = 0;
            if (!empty($rider)) {
                $riderid = $rider['id'] ?? 0;
                if ($rider['user_id'] != $this->request->user_id) {
                    $this->result([], 1, '该账号已被其它微信账号绑定,非当前微信可操作');
                }
            }
            //查到骑手id 再查看街道信息是否已经存在
            if (!empty($riderid)) {
                $riderstreet = (new RiderStreet())->where(['riderid' => $riderid])->find();
                if (!empty($riderstreet) && $riderstreet['status'] == 1) {
                    $this->result([], 1, '当前街道已在审核中，请登陆账号街道管理内查看');
                }
                if (!empty($riderstreet) && $riderstreet['status'] == 2) {
                    $this->result([], 1, '当前街道审核已通过，请登陆账号街道管理内查看');
                }
            }
            //保存数据
            $addstreet = [
                'riderid' => $riderid,
                'agentid' => $streets['agentid'] ?? 0,
                'province' => $streets['province'],
                'city' => $streets['city'],
                'area' => $streets['area'],
                'street' => $streets['street'],
                'status' => 1,
                'lat' => $data['lat'],
                'lon' => $data['lng']
            ];
            Db::startTrans();
            try {
                //如果有骑手信息就更新 没有就保存
                if (!empty($rider)) {
                    (new RiderList())->allowfield(true)->save($save, ['id' => $rider['id']]);
                } else {
                    $riderid = (new RiderList())->insertGetId($save);
                }
                $addstreet['riderid'] = $riderid;
                //查询街道有没有就提交 已有就更新
                if (empty($riderstreet)) {
                    (new RiderStreet())->allowfield(true)->save($addstreet);
                } else {
                    (new RiderStreet())->allowfield(true)->save($addstreet, ['id' => $riderstreet['id']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '提交失败，请重试');
            }
            $this->result([], 0, '申请成功,您可登陆账号查看审核状态');
        } else {
            $list = (new RiderList())->field('user_id,password', true)->where(['user_id' => $this->request->user_id])->find();
            if (!empty($list)) {
                $riderstreet = (new RiderStreet())->where(['riderid' => $list['id']])->find();
                if (!empty($riderstreet)) {
                    $list['province'] = $riderstreet['province'];
                    $list['city'] = $riderstreet['city'];
                    $list['area'] = $riderstreet['area'];
                    $list['street'] = $riderstreet['street'];
                    $list['province_text'] = (new Region())->where(['area_code' => $riderstreet['province']])->value('name');
                    $list['city_text'] = (new Region())->where(['area_code' => $riderstreet['city']])->value('name');
                    $list['area_text'] = (new Region())->where(['area_code' => $riderstreet['area']])->value('name');
                    $list['street_text'] = (new Region())->where(['id' => $riderstreet['street']])->value('name');
                    $list['status'] = $riderstreet['status'];
                }
            }
            $this->result($list, 0, '获取成功');
        }
    }
}
